package org.skipper.samples.spring.transaction.service;

import org.skipper.samples.spring.transaction.entity.UserInfo;
import org.skipper.samples.spring.transaction.mapper.UserInfoMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * Description: 仅方法进行事务注释
 *
 * @author shoujian
 * Date: 2022-02-08
 * Time: 10:51 AM
 */
@Component
public class MethodTransaction {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Transactional(readOnly = true)
    public UserInfo getUserInfoReadonly() {
        return userInfoMapper.selectById(1L);
    }

    @Transactional(readOnly = true)
    public void updateUserInfoReadonly() {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(1L);
        userInfo.setNickname("新的昵称");
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 若rollbackFor = SQLException.class,则只有出现SQLException时才会回滚
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfoRollback() throws Exception {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(1L);
        userInfo.setNickname("新的昵称");
        userInfoMapper.updateById(userInfo);

        throw new Exception("测试回滚");
    }

}
